define(['../../common/service'], function( http){
    var userAudienceKit = {
        initLocation : function (_config){
            var _this = this;
            var _locationArea = _config.locationArea;

            _locationArea.find(".location-select2").empty().select2({
                placeholder:  I18N.getText('management', 'addLocations'),
                multiple: true,
                allowClear: false,
                width: '100%',
                minimumInputLength: 1,
                maximumSelectionLength:25,
                ajax:{
                    type:'POST',
                    url: cors_config.api_host + '/search/searchAdgeolocation',
                    dataType: 'json',
                    delay: 250,
                    data: function (query) {
                        return{
                            param:JSON.stringify({
                                q: query.term,
                                locale: I18N.language,
                                cType: _locationArea.find(".location-type").data("val")
                            })
                        }
                    },
                    xhrFields: {
                        withCredentials: true
                    },
                    //配置返回数据格式
                    processResults: function (res) {
                        var opts = {
                            results: []
                        };
                        var data = res.data;
                        $(data).each(function(i, v) {
                            var _countryCode = v.countryCode || v.country_code;
                            if (v.type == 'country'){
                                v.id = _countryCode;
                                v.text = v.name;
                            } else {
                                v.id = v.key;
                                v.text = v.name + '(' + _countryCode +')';
                            }
                            v.isClude = _locationArea.find(".location-clude").data("val");

                            if (_config.locationIncludeKeys && _config.locationIncludeKeys.length && _config.locationIncludeKeys.indexOf(v.id) == -1){
                                v.disabled = 'disabled';
                                v.isNotInclude = true;
                            }

                            if (!_config.locationExcludeKeys || _config.locationExcludeKeys.indexOf(v.id) == -1){
                                //不属于不投放就显示
                                opts.results.push(v);
                            }
                        });
                        return opts;
                    },
                    cache: false
                },
                templateResult : function(_location){
                    if (_location.isNotInclude){
                        return $('<span>' + _location.text +'</span><span class="location-r">' + I18N.getText('management', 'onlyRegion')  +'</span>');
                    } else {
                        var _s = '<span>' + _location.text +'</span>' +
                            '<span class="location-t">';
                        if (_location.type == 'country'){
                            _s += "国家";
                        } else if (_location.type == 'region'){
                            _s += "州/省";
                        } else if (_location.type == 'city'){
                            _s += "城市";
                        } else if (_location.type == 'zip'){
                            _s += "邮编";
                        } else if (_location.type == 'electoral_district'){
                            _s += "国会选区";
                        }  else if (_location.type == 'geo_market'){
                            _s += "市场";
                        } else if (_location.type == 'custom_location'){
                            _s += "自定义";
                        }

                        _s += '</span>';
                        return $(_s);
                    }
                },
                templateSelection : function(_location){
                    var _text = ''
                    var _countryCode = _location.countryCode || _location.country_code || _location.country;
                    if (_location.type == 'country'){
                        _text = _location.name;
                    } else if (_location.type == 'region'){
                        _text = _location.name + '(' + _countryCode +')';
                    } else if (_location.type == 'city'){
                        if (_location.radius && _location.radius > 0){
                            _text = _location.name + '+ ' + _location.radius + (_location.distance_unit ? _location.distance_unit : I18N.getText('management', 'kilometer')) + '(' + _countryCode +')';
                        } else {
                            _text = _location.name + '(' + _countryCode +')';
                        }

                    } else if (_location.type == 'zip'){
                        _text = _location.name + '(' + _countryCode +')';
                    } else if (_location.type ==  'electoral_district'){
                        _text = _location.name + '(' + _countryCode +')';
                    } else if (_location.type == 'geo_market'){
                        _text = _location.name + ',DMA®' + '(' + _countryCode +')'
                    } else if (_location.type ==  'custom_location'){
                        _text = '(' +  _location.latitude + ',' + _location.longitude + ')' +  '+ ' + _location.radius +(_location.distance_unit ? _location.distance_unit : I18N.getText('management', 'kilometer')) + '(' + _countryCode +')';
                    }

                    return _text  + '[' + (_location.isClude == 1 ? I18N.getText('management', 'include') :I18N.getText('management', 'exclude'))+ ']';
                }
            }).off("select2:unselect").on("select2:unselect",function(e){
                var o = e.params.data;
                _locationArea.find(".location-select2").find("option[value="+o.id+"]").remove();
                if (_config.changeCallBack){
                    _config.changeCallBack();
                }
            }).off("select2:select").on("select2:select",function(e){
                if (_config.changeCallBack){
                    _config.changeCallBack();
                }
            }).off("select2:open").on("select2:open",function(){
                //地区支持粘贴
                _this.bindCopyToLocation(_locationArea);  //绑定copy事件
            })
        },
        bindCopyToLocation : function(onlyLB, _changeCallBack){
            var self = this;
            var isCtrlKey   = false,		 //用于处理copy监控偶发性失效问题
                isLoading   = false;		 //用于处理重复粘贴

            //禁用鼠标右键粘贴
            onlyLB.off('contextmenu');
            onlyLB.on('contextmenu', function(e){
                e.stopPropagation()
                return false;
            });
            //判定是否为copy操作。触发时间在select2.query之前
            $('.select2-search__field', onlyLB).off('keydown');
            $('.select2-search__field', onlyLB).on('keydown', function(e){
                if(e.ctrlKey|| e.metaKey){
                    isCtrlKey = true;
                }
            });

            //绑定copy事件。触发时间在select2.query之后
            onlyLB.off('keyup');
            onlyLB.on('keyup',function(e){
                var onlyLB =$(this),
                    loc = $('.location-select2', this);
                if(!isLoading && isCtrlKey && e.keyCode == 86){
                    var par = {
                        countries: $('.select2-search__field', this).val() || '',
                        locale:I18N.language
                    };
                    isLoading = true;
                    Kit.loading.show(onlyLB);
                    loc.select2('close');
                    http.work('/search/searchAdgeolocationList', par, 'POST').then(function(res){
                        if(res.flag == 'success'){
                            if (res.data.length != 0 ){
                                var preload_data = loc.select2('data'),
                                    _region = [];
                                $.each(preload_data, function(i, v) {
                                    _region.push(v);
                                });

                                var isChange = false;
                                $.each(res.data,function(i,v){
                                    //去除重复的国家
                                    var index = Kit.keyIn(_region, v.countryCode, "id");
                                    if (index == -1){
                                        isChange = true;
                                        v.id = v.countryCode;
                                        v.text = v.name + '('+ v.countryCode +')';
                                        v.isClude = $("div.ndp-drop-wrapper[name=location-clude]").data("val");
                                        _region.push(v);
                                    }
                                });

                                loc.select2('data', _region);
                                if (isChange){
                                    if (_changeCallBack){
                                        __changeCallBack();
                                    }
                                }
                            }
                        }
                        isLoading = false;
                        Kit.loading.hide(onlyLB);
                    });
                }
                window.setTimeout(function(){
                    isCtrlKey = false;
                },300);
                return false;
        });

    },
        initAge : function(_config){
                var min_age = 13;
                var max_age = 65;
                var c_min_age = min_age;
                var c_max_age = max_age;
                var min_ages = [];
                var max_ages = [];
                for (var i = min_age; i <= max_age; i++){
                    var _i = {val : i};
                    if (i < c_min_age || i > c_max_age){
                        _i.disable = true;
                        _i.name = i + "(" + I18N.getText('management', 'limitByProductManagement') + ")"
                    } else {
                        _i.name = i;
                    }

                    min_ages.push(_i);
                    max_ages.push(_i);
                }

                var _initMinAge = _config && _config.age_min  ? _config.age_min : min_age;
                var _initMaxAge = _config && _config.age_max ? _config.age_max  : max_age;
                var _minDrop = $("div.ndp-drop-wrapper[name=min-age]", _config.container).empty().drop({
                    data:min_ages,
                    caret:"glyphicon-menu-right"
                }).off("ITEM_CHANGE").on("ITEM_CHANGE",function(e){
                    if (_config && _config.changeCallBack){
                        _config.changeCallBack();
                    }
                }).off("ITEM_CLICK").on("ITEM_CLICK",function(e){
                    var c_mi  = e.originalEvent.data.val;
                    var c_mx  =  $("div.ndp-drop-wrapper[name=max-age]", _config.container).data("val");
                    if (c_mx < c_mi){
                        _maxDrop.val({name :  c_mi , val : c_mi});
                    }
                });
                _minDrop.val({name : _initMinAge , val : _initMinAge});

                var _maxDrop =  $("div.ndp-drop-wrapper[name=max-age]", _config.container).drop({
                    data:max_ages,
                    caret:"glyphicon-menu-right"
                }).off("ITEM_CHANGE").on("ITEM_CHANGE",function(e){
                    if (_config && _config.changeCallBack){
                        _config.changeCallBack();
                    }
                }).off("ITEM_CLICK").on("ITEM_CLICK",function(e){
                    var c_mx   = e.originalEvent.data.val;
                    var c_mi  =  $("div.ndp-drop-wrapper[name=min-age]", _config.container).data("val");
                    if (c_mx < c_mi){
                        _minDrop.val({name :  c_mx , val : c_mx});
                    }
                });
                _maxDrop.val({name :  _initMaxAge , val : _initMaxAge});
        },
        buildLocation : function(_config){
            var self = this;
            var result = {};
            var _locations = _config.locationArea.select2("data");
            if  (_locations && _locations.length > 0){
                $.each(_locations, function(i, _location){
                    if (_location.isClude && (_location.isClude == "1" || _location.isClude == 1)){
                        if (!result.geo_locations){
                            result.geo_locations = {};
                        }
                        //包括
                        if (_config.locationIncludeKeys && _config.locationIncludeKeys.length  && self.locationIncludeKeys.indexOf(_location.id) == -1){
                            //投了未指定的地区
                            result.isConflict = true;
                        }

                        if (_config.locationExcludeKeys && _config.locationExcludeKeys.length  && self.locationExcludeKeys.indexOf(_location.id) > -1){
                            //投了已排除的地区
                            result.isConflict = true;
                        }

                        self.buildLocations(result.geo_locations, _location)
                    } else {
                        if (!result.excluded_geo_locations){
                            result.excluded_geo_locations = {};
                        }
                        self.buildLocations(result.excluded_geo_locations, _location)
                    }
                });
            }

            return result;
        },
        buildLocations : function(_locations, _location){
        if (_location.type == 'country'){
            if (!_locations["countries"]){
                _locations["countries"] = [];
            }
            _locations["countries"].push(_location.country_code || _location.countryCode)
        } else if (_location.type == 'region'){
            if (!_locations["regions"]){
                _locations["regions"] = [];
            }
            _locations["regions"].push({"key":_location.id,"name":_location.name,"country":_location.country_code || _location.countryCode});
        } else if (_location.type == 'city'){
            if (!_locations["cities"]){
                _locations["cities"] = [];
            }
            var _city = {"distance_unit":_location.distance_unit || "kilometer",
                "key":_location.id,"name":_location.name,"radius":_location.radius || 40,"country":_location.country_code || _location.countryCode};
            if (_location.region){
                _city.region = _location.region;
            }
            _locations["cities"].push(_city);
        } else if (_location.type == 'zip'){
            if (!_locations["zips"]){
                _locations["zips"] = [];
            }
            _locations["zips"].push ({"key":_location.id,"name":_location.name,"country":_location.country_code || _location.countryCode});
        } else if (_location.type == 'geo_market'){
            if (!_locations["geo_markets"]){
                _locations["geo_markets"] = [];
            }
            _locations["geo_markets"].push ({"key" : _location.id,"name" : _location.name,"country" : _location.country_code || _location.countryCode});
        } else if (_location.type == 'electoral_district'){
            if (!_locations["electoral_districts"]){
                _locations["electoral_districts"] = [];
            }
            _locations["electoral_districts"].push ({"key" : _location.id,"name" : _location.name,"country" : _location.country_code || _location.countryCode});
        } else if (_location.type == 'custom_location'){
            if (!_locations["custom_locations"]){
                _locations["custom_locations"] = [];
            }
            _locations["custom_locations"].push ({
                "distance_unit" : _location.distance_unit,
                "latitude" : _location.latitude,
                "longitude" : _location.longitude,
                "radius" : _location.radius,
                "country" : _location.country ||  _location.country_code || _location.countryCode
            });
        } else {
            console.log("其他地区类型");
        }
    }
    }

    return userAudienceKit;
})
